var express = require('express');
var url = require('url');
var app = require('express').createServer();

app.listen(8080);
app.use(express.bodyParser());

var request = [];
var message = [];
var name = {};

app.get('/connect', function(req, res) {
	var data = url.parse(req.url, true).query;
	var n = data.name;
	if (typeof name[n] !== 'number') {
		name[n] = 1;
		responseData(res, {'error':''});
		return;
	}
	responseData(res, {'error': 'Your name is conflicted!'});
});

app.post('/chat', function(req, res) {
	var data = req.body;
	if (typeof data !== 'object') return;

	if (typeof request[data.id] !== 'object') {
		request[data.id] = [];
	}
	
	if (data.type == 'send_message') {
		message.push(data);
	}

	if (data.type == 'listen') {
		request[data.id].push(res);
	}
	
	req.connection.on('close', function() {
		var len = request[data.id].length;
		for(var i = 0; i < len; i++) {
			if (res == request[data.id][i]) {
				request[data.id].splice(i, 1);
				break;
			}
		}
	});
});

setInterval(function() {
	var time = new Date().getTime() - 30000;
	var len = message.length;
	for(var i = 0; i < len; i++) {
		if (typeof message[i] !== 'object') {
			continue;
		}
		var id = message[i].id;
		var numReq = request[id].length;
		if (numReq > 0) {
			for(var j = 0; j < numReq; j++) {
				var res = request[id][j];
				if (res.time < time) {
					continue;
				}
				responseData(res, message[i]);
			}
			request[id] = [];
			delete message[i];
		}
	}
}, 1000);

function responseData(res, data) {
	res.setHeader('Access-Control-Allow-Origin', 'http://myrun.com');
	res.statusCode = 200;
	res.end(JSON.stringify(data));
}